<?php
if (version_compare(PHP_VERSION, '5.2', '<'))
{
    die('Mychoonz requires at least PHP version 5.2');
}

define('mcz_BASE_DIR',           dirname(__FILE__) . '/');
define('mcz_APP_DIR',            mcz_BASE_DIR . 'app/');
define('mcz_LIB_DIR',            mcz_APP_DIR . 'lib/');
define('mcz_VIEWS_DIR',          mcz_APP_DIR . 'views/');
define('mcz_CONTROLLERS_DIR',    mcz_APP_DIR . 'controllers/');
define('mcz_MODELS_DIR',         mcz_APP_DIR . 'models/');
define('mcz_CACHE_DIR',          mcz_APP_DIR . 'cache/');
define('mcz_DEFAULT_CONTROLLER', 'index');
define('mcz_DEFAULT_ACTION',     'index');
define('mcz_WS_DIR',             mcz_APP_DIR . 'services/');

@(include(mcz_APP_DIR . 'config.php'))
	or die('Edit ' . mcz_APP_DIR . 'config.php.dist and rename it to '
		   . mcz_APP_DIR . 'config.php');

set_include_path(  mcz_CONTROLLERS_DIR . PATH_SEPARATOR
                 . mcz_MODELS_DIR . PATH_SEPARATOR
				 . mcz_LIB_DIR . PATH_SEPARATOR
				 . '.'
                 );

function __autoload($class)
{
	$file = str_replace('_', '/', $class) . '.php';
    if(!include_once($file))
	{
		throw new Exception('Autoloader could not find ' . $file);
	}
}
mcz_Benchmark::start('request');
mb_internal_encoding('UTF-8');
date_default_timezone_set(mcz_TIME_ZONE);
ini_set('session.use_trans_sid', false);

// future internationalization ?
function T($string)
{
    return $string;
}

// enable / disabble url rewriting ?
function mczURL($string)
{
	if(!mcz_URL_REWRITING)
	{
		return mcz_BASE_URL . 'index.php?/' . $string;
	}
	return mcz_BASE_URL . $string;
}

// magic quotes must die.
//set_magic_quotes_runtime(0);
if(get_magic_quotes_gpc())
{
    function mczStripslashes_recursive($value)
	{
		if (is_array($value))
		{
			foreach($value as $index => $val)
			{
				$value[$index] = mczStripslashes_recursive($val);
			}
			return $value;
		}
		else
		{
			return stripslashes($value);
		}
	}
    $_GET    = mczStripslashes_recursive($_GET);
	$_POST   = mczStripslashes_recursive($_POST);
    $_COOKIE = mczStripslashes_recursive($_COOKIE);
}

if (mcz_APP_DEBUG)
{
    error_reporting(E_ALL | E_STRICT);
    ini_set('display_errors', true);
}
else
{
    error_reporting(0);
    ini_set('display_errors', false);
}

function mczSend404()
{
	$p = new mcz_XHTML(array('title' => 'page not found'));
	$p->add('<h1>404</h1><h2>Page not found.</h2>');
	$p->render(true);
}

function mczExceptionHandler(Exception $e)
{
    if($e->getCode() == 404)
    {
	    mczSend404();
	    return;
    }

    $errId = date('YmdHis');
    if(mcz_LOG_ERRORS)
    {
	    file_put_contents(mcz_APP_DIR . 'errors/' . $errId . '.err.txt',
					      serialize($e));
    }

    if(mcz_SEND_ERRORS)
    {
        $content = '';
        foreach($e->getTrace() as $trace)
        {
            $content.= print_r($trace, true);
        }
        mail(mcz_ADMIN_MAIL, mcz_APP_NAME . ' exception: ' . $e->getMessage(),
			 $content);
        // then exec error controller/method ?
    }

    if(mcz_APP_DEBUG)
    {
        $p = new mcz_XHTML(array('title' => 'shit happens'));
		$p->innerCss('
			body{font-family:monospace;}
		');
        $p->add('<h1>An exception occured</h1>
				<h2>You\'re lame and this application sucks. Here\'s why:</h2>
				<pre>' . htmlspecialchars(mcz_APP_NAME)
                . ' exception: ' . htmlspecialchars($e->getMessage())
				. '<br/>');
        foreach($e->getTrace() as $trace)
        {
            $p->add(htmlspecialchars(print_r($trace, true)));
        }
        $p->add('</pre>');
        $p->render(true);
    }
}
set_exception_handler('mczExceptionHandler');
mcz_ErrorHandler::initialize();

if(!is_file(mcz_DB_FILE))
{
    $tables = array(
	    new mcz_User(),
	    new mcz_Tune(),
	    new mcz_TuneIndex(),
	    new mcz_Role(),
	    new mcz_Permission(),
	    new mcz_RolePermission(),
	    new mcz_Playlist(),
	    new mcz_PlaylistTune()
    );
    $sql = '';
    foreach($tables as $table)
    {
	    $sql.= $table->getTableSql();
    }
    mcz_DB::getInstance()->exec($sql);

    mcz_Role::store('guest', array('search'));
    mcz_Role::store('trusted', array('search','download','tag'));

    $user = new mcz_User();
    $user->login = 'anonymous';
    $user->password = 'anonymous';
    $user->email = 'anonymous@nowhere.com';
    $user->setRole(mcz_Role::store('anonymous', array()));
    $user->active = false;
    $user->save();

    $user = new mcz_User();
    $user->login     = 'admin';
    $user->password  = sha1('admin');
    $user->email     = 'admin@host.com';
    $user->setRole(mcz_Role::store('admin', array('search','download','tag','delete','admin')));
    $user->save();

    chmod(mcz_DB_FILE, 0777);
}



if(!defined('mcz_CLI_MODE') and !defined('mcz_WS_MODE'))
{
	session_name('app_' . md5(mcz_APP_NAME));
	session_start();
	if(!isset($_SESSION['obj']))
	{
	    $_SESSION['obj'] = new mcz_Session();
	}
	// bypass dispatch loop if controller is set in get request
	if(isset($_GET['c']))
	{
	    $_GET['a'] = isset($_GET['a']) ? $_GET['a'] : 'index';
	    mcz_Dispatcher::executeAction($_GET['c'], $_GET['a'], array());
	}
	else
	{
	    if(isset($mczRoutes))
	    {
		    mcz_Dispatcher::addRoute($mczRoutes);
	    }
	    mcz_Dispatcher::dispatch();
	}
}